// 用户控制器
import { User } from "../model/index.js";
import { createToken } from "../utils/jwt.js";
export const list = async (req, res) => {
  res.send("user-list");
};

// 用户注册
export const registers = async (req, res) => {
  try {
    const user = new User(req.body);
    const userInfo = await user.save();
    let returnUser = userInfo.toJSON();
    // 移除密码字段
    delete returnUser.password;
    res.status(201).json(returnUser);
  } catch (error) {
    console.log(error);
    res.status(500).json({ code: 500, error: "服务器内部错误" });
  }
};

// 用户登陆
export const login = async (req, res) => {
  try {
    const user = await User.findOne(req.body);
    let returnUser = user.toJSON();
    const token = await createToken(returnUser);
    res.status(200).json({
      code: 200,
      data: { ...returnUser, token },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, error: "服务器内部错误" });
  }
};

// 编辑用户
export const update = async (req, res) => {
  try {
    const id = req.user._id;
    const user = await User.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    // 设置new为true，返回的是修改后的新数据
    res.status(200).json({
      code: 200,
      data: user,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, error: "服务器内部错误" });
  }
};

// 删除用户
export const remove = async (req, res) => {
  try {
    if (!req.query.id) {
      return res.status(400).json({ code: 400, error: "请传入用户id" });
    }
    const id = req.query.id;
    const user = await User.findByIdAndDelete(id);
    res.status(200).json({
      code: 200,
      data: user,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, error: "服务器内部错误" });
  }
};

// 上传用户头像
export const avatar = async (req, res) => {
  try {
    const { filename } = req.file;
    const avatarPath = `/avatar/${filename}`;
    // 更新用户头像
    const updatedUser = await User.findByIdAndUpdate(req.user._id, { avatar: avatarPath }, { new: true });
    res.status(200).json({
      code: 200,
      data: { userInfo: updatedUser },
      message: "头像上传成功",
    });
  } catch (error) {
    console.error("头像上传失败:", error);
    res.status(500).json({
      code: 500,
      error: "头像上传失败",
    });
  }
};

